<template>
  <div style="width: 100%;height: 100%;">
    <div id="realtimeContainer"></div>
  </div>
</template>

<script>
import pathNavigator from '@/assets/img/pathNavigator.png'
import icon from '@/assets/img/icon.svg'
import {getToken} from '@/utils/LocalDataUtil'
import {getMapLocationDown, getSignInfo, getPicPath} from '@/http/AppApi'
export default {
  props: {
    mapInfo: null,
    isClosed: false
  },
  data () {
    return {
      infoWindowShow: false,
      object3Dlayer: null,
      polygon: null,
      AMapUI: null,
      prism: null,
      text: null,
      AMap: null,
      map: null,
      zoom: 0,
      zoomAddTimes: 0,
      zoomMinusTimes: 0,
      currentGridIds: [],
      formData: {},
      gridZoom: {
        '06': 14.1, '05': 12.13, '04': 10.8, '03': 9.5
      },
      genderTransition: {
        '0': '未知的性别', '1': '男', '2': '女'
      }
    }
  },
  watch: {
    isClosed (newName, oldName) {
      if (newName) this.map.destroy()
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    init () {
      let viewMode = this.mapInfo.viewMode ? this.mapInfo.viewMode : '3D'
      this.AMap = window.AMap
      let mapConfig = {
        resizeEnable: true,
        zoom: 10.8,
        viewMode: viewMode,
        pitch: 40,
        cityName: '信阳市',
        center: [114.091104, 32.148489]
      }
      this.map = new AMap.Map('realtimeContainer', mapConfig)
      this.map.on('complete', this.mapComplete())
    },
    mapComplete () {
      if (this.mapInfo) {
        this.mapInfo.zoom && this.map.setZoom(this.mapInfo.zoom) // 重置缩放级别 string
        this.mapInfo.center && this.map.setCenter(this.mapInfo.center) // 重置中心点 string
        this.mapInfo.isFitView && this.map.setFitView() // 自动缩放地图到合适的视野级别
        this.mapInfo.isAddControl && this.map.addControl(this.mapInfo.controls) // 添加地图控件 Object
        this.mapInfo.mapStyle && this.map.setMapStyle(this.mapInfo.mapStyle) // 设置地图样式 String
        this.mapInfo.features && this.map.setFeatures(this.mapInfo.features) // 设置地图显示元素 Array
        this.mapInfo.status && this.map.setStatus(this.mapInfo.status) // 设置当前地图显示状态 object
        this.mapInfo.pitch && this.map.setPitch(this.mapInfo.pitch) // 设置地图俯仰角 即倾斜度 number
        this.mapInfo.pan && this.map.panBy(this.mapInfo.pan.x, this.mapInfo.pan.y) // 设置地图便偏移 object: number
        this.mapInfo.isZoomChangedEvt && this.map.on('zoomend', this.mapZoomEnd)
        this.mapInfo.isLoadPolygon && this.loadPolygon()
        this.mapInfo.isLoadMarker && this.loadMarker()
        this.mapInfo.isLoadTrack && this.loadTrackFn()
        if (this.mapInfo.isPrism) {
          this.map.AmbientLight = new AMap.Lights.AmbientLight([1, 1, 1], 0.5)
          this.map.DirectionLight = new AMap.Lights.DirectionLight([0, 0, 1], [1, 1, 1], 1)
        }
      }
      this.zoom = this.map.getZoom()
    },
    TrackInitPage (PathSimplifier) {
      let m = this
      let trackInfo = this.mapInfo.trackInfo
      let pathSimplifierIns = new PathSimplifier({
        zIndex: 100,
        map: m.map,
        getPath: function (pathData, pathIndex) {
          return pathData.path
        },
        getHoverTitle: function (pathData, pathIndex, pointIndex) {
          if (pointIndex >= 0) {
            return pathData.name + '，点:' + pointIndex + '/' + pathData.path.length
          }
          return pathData.name + '，点数量' + pathData.path.length
        },
        renderOptions: {renderAllPointsIfNumberBelow: 100}
      })
      let path = trackInfo.trackPath ? trackInfo.trackPath : []
      pathSimplifierIns.setData([{
        name: '轨迹0',
        path: path
      }])
      var navg0 = pathSimplifierIns.createPathNavigator(0, {
        loop: true,
        speed: 30,
        pathNavigatorStyle: {
          width: 30,
          height: 63,
          autoRotate: false,
          content: PathSimplifier.Render.Canvas.getImageContent(pathNavigator, onload, onerror)
        }
      })
      navg0.start()
    },
    loadTrackFn () {
      let m = this
      let AMapUI = window.AMapUI
      AMapUI.load(['ui/misc/PathSimplifier'], function (PathSimplifier) {
        if (!PathSimplifier.supportCanvas) {
          alert('当前环境不支持 Canvas！')
          return
        }
        setTimeout(m.TrackInitPage(PathSimplifier), 500)
      })
    },
    mapZoomEnd () {
      let zoom = this.map.getZoom()
      if (zoom > 14 && zoom > this.zoom) {
        this.zoom = zoom
        this.zoomMinusTimes = 0
        this.zoomAddTimes += 1
        if (this.zoomAddTimes === 1) {
          this.setMarkerIcon()
        }
      } else if (zoom <= 14 && zoom <= this.zoom) {
        this.zoomAddTimes = 0
        this.zoomMinusTimes -= 1
        if (this.zoomMinusTimes === -1) {
          for (const key in this.markers) {
            if (this.markers.hasOwnProperty(key)) {
              this.markers[key].setIcon()
            }
          }
        }
      }
      this.zoom = zoom
    },
    setMarkerIcon () {
      let m = this
      for (const key in this.markers) {
        if (this.markers.hasOwnProperty(key)) {
          getSignInfo(this.markers[key].userId).then(resp => {
            if (resp.code && resp.code === '200') {
              if (resp.data.photo && resp.data.photo !== '') {
                let url = getPicPath() + resp.data.photo + '?token=' + getToken()
                let cusIcon = new AMap.Icon({
                  size: new AMap.Size(60, 60),
                  image: url
                  // imageOffset: new AMap.Pixel(-9, -3)
                })
                m.markers[key].setIcon(cusIcon)
              } else {
                m.markers[key].setIcon(icon)
              }
            } else {
              m.markers[key].setIcon(icon)
            }
          })
        }
      }
    },
    // 创建marker群组
    loadMarker () {
      let markerData = this.mapInfo.markerInfo.markerData
      let markers = []
      let m = this
      for (const key in markerData) {
        if (markerData.hasOwnProperty(key)) {
          let marker = new AMap.Marker({
            position: [markerData[key].longitude, markerData[key].latitude],
            showPositionPoint: true
          })
          marker.userId = markerData[key].userId
          marker.lnglat = [markerData[key].longitude, markerData[key].latitude]
          marker.on('click', m.showInfoWindow)
          markers.push(marker)
        }
      }
      if (markers.length === 0) return ''
      this.markers = markers
      let overlayGroups = new AMap.OverlayGroup(markers)
      this.map.add(overlayGroups)
    },
    showInfoWindow (e) {
      let m = this
      getSignInfo(e.target.userId).then(resp => {
        if (resp.code && resp.code === '200') {
          this.map.setZoom(17)
          this.map.setCenter(e.target.lnglat)
          let userInfo = resp.data
          let memberType = userInfo.memberType === 0 ? '（网格长）' : '(网格员)'
          let phone = userInfo.phone !== '' && userInfo.phone ? userInfo.phone : '无'
          let gender = m.genderTransition[userInfo.sex] ? m.genderTransition[userInfo.sex] : '未说明的性别'
          let title = userInfo.name + '<span style="font-size:11px;color:#F00;">' + memberType + '</span>'
          let content = []
          content.push('网格：' + userInfo.gridName)
          content.push('电话：' + phone)
          content.push('性别：' + gender)
          let infoWindow = new AMap.InfoWindow({
            isCustom: true,
            content: m.createInfoWindow(title, content.join('<br/>')),
            offset: new AMap.Pixel(16, -45)
          })
          infoWindow.open(m.map, e.target.lnglat)
        }
      })
    },
    createInfoWindow (title, content) {
      let closeXSrc = 'https://webapi.amap.com/images/close2.gif'
      let info = document.createElement('div')
      info.className = 'custom-info input-card content-window-card'
      // 可以通过下面的方式修改自定义窗体的宽高
      // info.style.width = '400px'
      // 定义顶部标题
      let top = document.createElement('div')
      let titleD = document.createElement('div')
      let closeX = document.createElement('img')
      top.className = 'info-top'
      titleD.innerHTML = title
      closeX.src = closeXSrc
      closeX.onclick = this.closeInfoWindow
      top.appendChild(titleD)
      top.appendChild(closeX)
      info.appendChild(top)
      // 定义中部内容
      let middle = document.createElement('div')
      middle.className = 'info-middle'
      middle.style.backgroundColor = 'white'
      middle.innerHTML = content
      info.appendChild(middle)
      return info
    },
    closeInfoWindow () {
      this.map.clearInfoWindow()
    },
    loadPolygon () {
      this.currentGridIds = []
      let treeData = this.mapInfo.polygonInfo.treeData
      let m = this
      if (treeData && treeData instanceof Array) {
        if (treeData.length > 0) {
          for (const key in treeData) {
            if (treeData.hasOwnProperty(key)) {
              let level = treeData[key].levelCode
              m.map.setZoom(m.gridZoom[level])
              m.currentGridIds.push(treeData[key].id)
              m.loadMapFun(treeData[key].id)
            }
          }
        }
      }
    },
    loadGridMap (id) {
      var promise = new Promise(function (resolve, reject) {
        getMapLocationDown(id).then(resp => {
          if (resp.code && resp.code === '200') {
            resolve(resp.data)
          }
        })
      })
      return promise
    },
    loadMapFun (id) {
      let m = this
      this.loadGridMap(id).then(function (data) {
        for (const j in data) {
          if (data.hasOwnProperty(j)) {
            m.createPolygon(data[j])
          }
        }
        m.map.panBy(18, -124)
      })
    },
    createPolygon (p) {
      if (p) {
        if (this.currentGridIds.indexOf(p.targetId) > -1) {
          this.map.setCenter([p.longitude, p.latitude])
          return ''
        }
        let poly = {}
        if (p.mapColor) {
          poly.fillColor = p.mapColor
          poly.strokeColor = p.mapColor
        }
        if (p.mapArea) {
          poly.path = JSON.parse(p.mapArea)
          let polygon = new AMap.Polygon(poly)
          if (this.mapInfo.isPrism) {
            polygon.on('mouseover', this.polygonHoverEvt)
            polygon.on('mouseout', this.polygonOutEvt)
          }
          polygon.name = p.name
          polygon.path = poly.path
          polygon.color = poly.path
          polygon.fillColor = p.mapColor
          polygon.lnglat = [p.longitude, p.latitude]
          polygon.id = p.targetId
          polygon.polygon = polygon
          this.map.add(polygon)
        }
        if (p.longitude && p.latitude) {
          // 添加文本标注
          if (this.mapInfo.isAddTextMark) {
            let info = new AMap.Text({
              map: this.map,
              text: p.name,
              zIndex: 1,
              anchor: this.mapInfo.textMarkInfo.anchor,
              clickable: false,
              position: [p.longitude, p.latitude]
            })
            info.setStyle(this.mapInfo.textMarkInfo.infoStyle)
            this.map.add(info)
          }
        }
      }
    },
    polygonHoverEvt (e) {
      this.polygon = e.target.polygon
      this.polygon.setOptions({fillOpacity: 0, strokeOpacity: 0})
      this.object3Dlayer = new AMap.Object3DLayer({ zIndex: 3 })
      this.map.add(this.object3Dlayer)
      var name = e.target.name
      var path = e.target.path
      var height = 5000
      var color = e.target.fillColor
      var lnglat = e.target.lnglat
      this.prism = new AMap.Object3D.Prism({
        path: path,
        height: height,
        color: color
      })
      this.prism.transparent = true
      this.object3Dlayer.add(this.prism)
      this.text = new AMap.Text({
        text: name,
        verticalAlign: 'bottom',
        position: lnglat,
        height: 6000,
        style: {
          'background-color': 'transparent',
          '-webkit-text-stroke': 'red',
          '-webkit-text-stroke-width': '0.5px',
          'text-align': 'center',
          'border': 'none',
          'color': 'white',
          'font-size': '14px',
          'font-weight': 600
        }
      })
      this.text.setMap(this.map)
      let m = this
      this.text.on('mouseover', function () {
        m.object3Dlayer.add(m.prism)
        m.polygon.setOptions({fillOpacity: 0, strokeOpacity: 0})
        m.text.show()
      })
      this.text.on('mouseout', function () {
        m.object3Dlayer.remove(m.prism)
        m.polygon.setOptions({fillOpacity: 0.9, strokeOpacity: 0.9})
        m.text.hide()
      })
    },
    polygonOutEvt (e) {
      this.prism && this.object3Dlayer.remove(this.prism)
      this.text && this.text.hide()
      this.polygon && this.polygon.setOptions({fillOpacity: 0.9, strokeOpacity: 0.9})
    }
  },
  destroyed () {
    this.map && this.map.destroy()
  }
}
</script>

<style>
#realtimeContainer{
  width: 100%;
  height: 100%;
  z-index: 1;
}
.content-window-card {
  position: relative;
  box-shadow: none;
  bottom: 0;
  left: 0;
  width: auto;
  padding: 0;
}
.content-window-card p {
  height: 2rem;
}
.custom-info {
  border: solid 1px silver;
  border-radius: 5px 5px 0 0;
}
div.info-top {
  position: relative;
  background: none repeat scroll 0 0 #F9F9F9;
  border-bottom: 1px solid #CCC;
  border-radius: 5px 5px 0 0;
}
div.info-top div {
  display: inline-block;
  color: #333333;
  font-size: 14px;
  font-weight: bold;
  line-height: 31px;
  padding: 0 10px;
}
div.info-top img {
  position: absolute;
  top: 10px;
  right: 10px;
  transition-duration: 0.25s;
}
div.info-top img:hover {
  box-shadow: 0px 0px 5px #000;
}
div.info-middle {
  font-size: 12px;
  padding: 10px 6px;
  line-height: 20px;
}
#realtimeContainer .amap-icon img{
  width: 60px;
  height: 60px;
}
</style>
